/*var mongoose=require('mongoose');
var config=require('../config');
var mongodb = require('mongodb');*/
var mongoose=require('./mongoConn');
var Schema=mongoose.Schema;
/*var db=mongoose.createConnection(config.db_url);
db.on('error',function(error){
    db.close();
    console.log(error);
});

db.on('close', function () {
    db.open(config.db_url);
    console.log("重新连接mongo");
});*/

var prizeSchema = new Schema({
    name: String, //商品名称
    price:String, //商品价格
    imgurl:String, //商品图片
    taobao_url:String, //商品淘宝链接
    wechat_productId:String//微信商品ID
});

//var Prize = db.model("Prize", prizeSchema);
var Prize = mongoose.model("Prize", prizeSchema);

Prize.prototype.findAllPrize=function(callback){
    Prize.find({},function(err,datas){
        return callback(err,datas);
    })
}

Prize.prototype.findPrizeById=function (prizeid,callback){
    Prize.find({_id:prizeid}, function(err, datas){
        return callback(datas);
    });
}

Prize.prototype.removeIdById=function (prizeid,callback){
    Prize.remove({_id:prizeid}, function(err){
        return callback(err);
    });
}

Prize.prototype.updatePrizeById=function(prizeid,name,price,imgurl,taobao_url,wechat_productId,callback){
    Prize.update({_id:prizeid},{name:name,price:price,imgurl:imgurl,taobao_url:taobao_url,wechat_productId:wechat_productId},function(err){
        return callback(err);
    })
}

Prize.prototype.findForPage=function(obj,callback){
    var q=obj.search||{};                                       //查询条件
    var col=obj.columns||{};                                    //返回字段
    var query=Prize.find(q,col).skip(obj.page.skipFrom).limit(obj.page.limit);

    query.exec(function(err, datas) {
        if (err) {
            callback(err, null, null);
        } else {
            Prize.count(q, function(err, count) {
                if (err) {
                    callback(err, null, null);
                } else {
                    var pageCount = Math.ceil(count / obj.page.limit);
                    callback(null,count,pageCount, datas);
                }
            });
        }
    });
}

module.exports = Prize;